
const mongoose = require('mongoose')
const { Schema } = mongoose

// 分类字段
const CategorySchema = new Schema({
    name: { type: String },
    parent: {
        type: mongoose.SchemaTypes.ObjectId,  // mongoose Id 类型是 ObjectId
        ref: 'Category' // 关联 Category 这个模型，使用 populate 就可以填充查询数据
    }  
})

// 以给定名称创建一个虚拟类型
CategorySchema.virtual('children', {
    localField: '_id',
    foreignField: 'parent',
    justOne: false,
    ref: 'Category'
})

CategorySchema.virtual('newsList', {
    localField: '_id',
    foreignField: 'categories',
    justOne: false,
    ref: 'Article'
})

module.exports = mongoose.model('Category', CategorySchema)